﻿module Sustainalytics.GovernanceReports {

    import Common = Sustainalytics.Common;
    import Pager = Sustainalytics.Pager;

    // News List controller
    export class CompanyViewController {

        // specifies whether current controller is in loading state
        public isLoading: boolean;

        // controller scope
        public $scope: ng.IScope;

        // services
        private $q: ng.IQService;
        private $location: ng.ILocationService;
        private $routeParams: ng.route.IRouteParamsService;
        private governanceService: GovernanceService;
        private notificationFactory: INotificationFactory;
        protected LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService;
        private $modal: IModal;
        private companyId: string;


        public companyProfile: GovernanceProfileDto;
        public companyName: string;
        public hasProfile: boolean;
        // Ctor.
        constructor($scope: ng.IScope, $q: ng.IQService, $location: ng.ILocationService, $routeParams: ng.route.IRouteParamsService, GovernanceService, notificationFactory: INotificationFactory, $modal: IModal, LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService) {
            var ctx = this;

            $scope['governanceForCompany'] = ctx;

            ctx.$scope = $scope;
            ctx.$q = $q;
            ctx.$location = $location;
            ctx.$routeParams = $routeParams;
            ctx.governanceService = GovernanceService;
            ctx.notificationFactory = notificationFactory;
            ctx.LongRunningTaskManagerService = LongRunningTaskManagerService;
            ctx.$modal = $modal;
            ctx.companyId = ctx.$routeParams['id'];

            // load all required data
            ctx.getCompany();
            ctx.getCompanyProfileAndAlerts(); 
        }

        public getCompany() {
            var ctx = this;
            ctx.isLoading = true;

            // get news items
            var companyProfilePromise: ng.IPromise<GovernanceProfileDto> = ctx.governanceService.getCompanyById(ctx.companyId);

            companyProfilePromise.then(function (corpData) {
                ctx.companyName = corpData['data'].companyName;
            });

            companyProfilePromise.finally(function () {
                ctx.isLoading = false;
            });
        }

        // get profile with alerts
        public getCompanyProfileAndAlerts() {
            var ctx = this;
            ctx.isLoading = true;

            // get news items
            var companyProfilePromise: ng.IPromise<GovernanceProfileDto> = ctx.governanceService.getCompanyProfileAndAlerts(ctx.companyId);

            // on success set list of news
            companyProfilePromise.then(function (data) {
                if (data['data'].errorCode == 7000) {
                    ctx.hasProfile = false;
                }
                else {
                    ctx.hasProfile = true;
                    ctx.companyProfile = data['data'];

                    console.log(ctx.companyProfile);
                }
            });

            companyProfilePromise.finally(function () {
                ctx.isLoading = false;
            });
        }

        // switch to add profile mode
        public addProfile() {
            var ctx = this;
            var modalInstance = ctx.$modal.open(
                {
                    templateUrl: 'Views/GovernanceReports/governance_reports_profileAdd.tpl.html',
                    controller: 'ProfileAddController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve:
                    {
                        companyProfile: function () {
                            return ctx.companyProfile;
                        },
                        companyName: function () {
                            return ctx.companyName;
                        }
                    }
                });

            modalInstance.result.then((out) => {
                ctx.companyProfile = out['companyProfile'];
                var noSave = out['noSave'];
                if (!noSave)
                    ctx.hasProfile = true;
            });
        }

        // switch to edit profile mode
        public editProfile() {
            var ctx = this;
            var modalInstance = ctx.$modal.open(
                {
                    templateUrl: 'Views/GovernanceReports/governance_reports_profileAdd.tpl.html',
                    controller: 'ProfileAddController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve:
                    {
                        companyProfile: function () {
                            return ctx.companyProfile;
                        },
                        companyName: function () {
                            return ctx.companyName;
                        }
                    }
                });

            modalInstance.result.then((out) => {
                ctx.companyProfile = out['companyProfile'];
            });
        }

        public downloadGovernancePDF(fileId: string, fileName: string) {
            var ctx = this;
            var taskNumber = 202;
            var data = { fileId: fileId, fileName: fileName };
            var promise = ctx.LongRunningTaskManagerService.runTask(fileName + "_" + moment().format("DD-MM-YYYY"), JSON.stringify(data), taskNumber, true, null);
        }

        public downloadGovernanceFileEnabled(fileId: string, fileName: string): boolean {
            var ctx = this;
            var result = false;

            if (fileId != undefined && fileName != undefined) {
                result = true;
            }
            return result;
        }

        // delete selected profile
        public deleteProfile() {
            var ctx = this;


            var modalInstanceDelete = ctx.$modal.open({
                templateUrl: 'Views/GovernanceReports/governance_report_deleteProfile.tpl.html',
                controller: 'DeleteCheckController',
                size: 'lg',
                backdrop: 'static'
            });

            modalInstanceDelete.result.then((out) => {
                if (out['deleteCheck'] == true) {
                    ctx.companyProfile = new GovernanceProfileDto();

                    // delete alert
                    var deleteProfilePromise: ng.IPromise<GovernanceProfileDto> = ctx.governanceService.deleteProfile(ctx.companyId);

                    deleteProfilePromise.then(function () {
                    });

                    deleteProfilePromise.finally(function () {
                        //ctx.getCompanyProfileAndAlerts();
                        ctx.hasProfile = false;
                    });
                }
            });
        }

        // switch to add alert mode
        public addAlert() {
            var ctx = this;
            var modalInstance = ctx.$modal.open(
                {
                    templateUrl: 'Views/GovernanceReports/governance_reports_alertAdd.tpl.html',
                    controller: 'AlertAddController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve:
                    {
                        currentAlert: function () {
                            return null;
                        },
                        companyProfile: function () {
                            return ctx.companyProfile;
                        },
                        companyName: function () {
                            return ctx.companyName;
                        }
                    }
                });

            modalInstance.result.then((out) => {
                ctx.companyProfile = out['companyProfile'];
            });
        }

        // switch to edit news mode
        public editAlert(alert: GovernanceAlertDto) {
            var ctx = this;
            var modalInstance = ctx.$modal.open(
                {
                    templateUrl: 'Views/GovernanceReports/governance_reports_alertAdd.tpl.html',
                    controller: 'AlertAddController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve:
                    {
                        currentAlert: function () {
                            console.log(alert);
                            return alert;
                        },
                        companyProfile: function () {
                            return ctx.companyProfile;
                        },
                        companyName: function () {
                            return ctx.companyName;
                        }
                    }
                });

            modalInstance.result.then((out) => {
                ctx.getCompanyProfileAndAlerts();
            });
        }

        // delete selected alert
        public deleteAlert(alert: GovernanceAlertDto) {
            var ctx = this;

            var modalInstanceDelete = ctx.$modal.open({
                templateUrl: 'Views/GovernanceReports/governance_report_deleteAlert.tpl.html',
                controller: 'DeleteCheckController',
                size: 'lg',
                backdrop: 'static'
            });

            modalInstanceDelete.result.then((out) => {
                if (out['deleteCheck'] == true) {
                    //list of alerts without the alert that we want to delete
                    var newAlers = ctx.companyProfile.alerts
                        .filter(function (el) {
                        return el.id !== alert.id;
                    });

                    ctx.companyProfile.alerts = newAlers;
   
                    // delete alert
                    var deleteAlertPromise: ng.IPromise<GovernanceProfileDto> = ctx.governanceService.saveProfile(ctx.companyProfile);

                    deleteAlertPromise.then(function () {
                    });
                }
            });
        }
    }

    // register controller with News Angular module
    angular.module('Sustainalytics.GovernanceReports').controller('CompanyViewController', function ($scope: ng.IScope, $q: ng.IQService, $location: ng.ILocationService, $routeParams: ng.route.IRouteParamsService, GovernanceService, notificationFactory: INotificationFactory, $modal: IModal, LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService) {
        var ctrl = new CompanyViewController($scope, $q, $location, $routeParams, GovernanceService, notificationFactory, $modal, LongRunningTaskManagerService);
        return ctrl;
    });
}